package com.party.admin.web.controller.operation;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Sets;
import com.party.core.utils.MyBeanUtils;
import com.party.admin.web.dto.AjaxResult;
import com.party.common.paging.Page;
import com.party.common.utils.LangUtils;
import com.party.common.utils.StringUtils;
import com.party.core.model.serviceguide.ServiceGuideRelation;
import com.party.core.model.serviceguide.ServiceGuideType;
import com.party.core.service.serviceguide.IServiceGuideRelationService;
import com.party.core.service.serviceguide.IServiceGuideTypeService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;

/**
 * @program: party
 * @description: 企业服务类型控制器
 * @author: Hua Qunhao
 * @create: 2019-01-08 16:45
 */
@Controller
@RequestMapping(value = "/service/article/guidetype")
public class ServiceGuideTypeController {
    @Autowired
    private IServiceGuideTypeService serviceGuideTypeService;

    @Autowired
    private IServiceGuideRelationService serviceGuideRelationService;

    Logger logger = LoggerFactory.getLogger(ServiceGuideTypeController.class);


    /**
     * 指南分类列表
     *
     * @param serviceGuideType 类型
     * @param page       分页参数
     * @return 交互数据
     */
    @RequestMapping(value = "list")
    public ModelAndView list(ServiceGuideType serviceGuideType, Page page) {
        page.setLimit(10);
        ModelAndView modelAndView = new ModelAndView("operation/serviceguide/serviceGuideTypeList");
        List<ServiceGuideType> list = serviceGuideTypeService.listPage(serviceGuideType, page);
        modelAndView.addObject("list", list);
        modelAndView.addObject("page", page);
        return modelAndView;
    }


    /**
     * 指南分类视图
     *
     * @param serviceGuideType 分类信息
     * @return 交互数据
     */
    @RequestMapping(value = "serviceGuideTypeView")
    public ModelAndView serviceGuideTypeForm(ServiceGuideType serviceGuideType) {
        ModelAndView modelAndView = new ModelAndView("operation/serviceguide/serviceGuideTypeView");
        if (StringUtils.isNotEmpty(serviceGuideType.getId())) {
            serviceGuideType = serviceGuideTypeService.get(serviceGuideType.getId());

            modelAndView.addObject("serviceGuideType", serviceGuideType);
        }
        return modelAndView;
    }


    /**
     * 验证分类唯一性
     *
     * @param name 分类名称
     * @return
     */
    @ResponseBody
    @RequestMapping("verifyName")
    public AjaxResult verifyName(String name, String id) {
        if (StringUtils.isEmpty(name)) {
            return AjaxResult.error("分类名称不能为空");
        }
        ServiceGuideType serviceGuideType = serviceGuideTypeService.findServiceGuideTypeByName(name);
        if (serviceGuideType != null && !(serviceGuideType.getId().equals(id))) {
            return AjaxResult.error("分类名称已存在");
        }
        return AjaxResult.success();
    }


    /**
     * 删除分类
     *
     * @param id 分类id
     * @return
     */
    @ResponseBody
    @RequestMapping("delete")
    public AjaxResult delete(String id) {
        if (StringUtils.isEmpty(id)) {
            return AjaxResult.error("id不能为空");
        }
        ServiceGuideRelation serviceGuideRelation = new ServiceGuideRelation();
        serviceGuideRelation.setSgtId(id);
        List<ServiceGuideRelation> list = serviceGuideRelationService.list(serviceGuideRelation);
        if (list!=null && list.size() > 0) {
            return AjaxResult.error("分类下存在服务,不能直接删除");
        }
        serviceGuideTypeService.delete(id);
        return AjaxResult.success();
    }


    /**
     * 指南分类保存
     *
     * @param serviceGuideType 服务分类
     * @return 交互数据
     */
    @ResponseBody
    @RequestMapping(value = "save")
    public AjaxResult save(ServiceGuideType serviceGuideType, BindingResult result) {
        // 数据验证
        if (result.hasErrors()) {
            List<ObjectError> allErros = result.getAllErrors();
            return AjaxResult.error(allErros.get(0).getDefaultMessage());
        }

        try {
            if (StringUtils.isNotEmpty(serviceGuideType.getId())) {
                ServiceGuideType t = serviceGuideTypeService.get(serviceGuideType.getId());

                MyBeanUtils.copyBeanNotNull2Bean(serviceGuideType, t);// 将编辑表单中的非NULL值覆盖数据库记录中的值
                serviceGuideTypeService.update(t);
            } else {
                serviceGuideTypeService.insert(serviceGuideType);
            }

            return AjaxResult.success();
        } catch (Exception e) {
            logger.error("保存分类异常", e);
            return AjaxResult.error("保存分类异常");
        }
    }


    /**
     * 获取分类列表
     *
     * @return 分类列表
     */
    @RequestMapping("/selectServiceGuideTypeList")
    public ModelAndView categoryList(ServiceGuideType category, Page page, String categoryIds) {
        page.setLimit(10);
        ModelAndView modelAndView = new ModelAndView("operation/serviceguide/selectServiceGuideTypeList");

        List<ServiceGuideType> epCategoryList = serviceGuideTypeService.listPage(category, page);

        modelAndView.addObject("list", epCategoryList);
        modelAndView.addObject("page", page);
        modelAndView.addObject("categoryIds", categoryIds);


        Set<String> allCategoryIds = Sets.newHashSet();
        if (StringUtils.isNotEmpty(categoryIds)) {
            allCategoryIds.addAll(Arrays.asList(categoryIds.split(",")));
        }
        if (allCategoryIds.size() > 0) {
            List<ServiceGuideType> mallCategories = serviceGuideTypeService.batchList(allCategoryIds, new ServiceGuideType(), null);
            mallCategories = LangUtils.transform(mallCategories, input -> {
                ServiceGuideType epCategory = new ServiceGuideType();
                epCategory.setId(input.getId());
                epCategory.setName(input.getName());
                return epCategory;
            });
            modelAndView.addObject("categoryJson", JSONObject.toJSONString(mallCategories));
        } else {
            modelAndView.addObject("categoryJson", JSONObject.toJSONString(new ArrayList<ServiceGuideType>()));
        }
        return modelAndView;
    }
}
